import os
from enum import Enum
from typing import List, Optional, Dict, Any
from datetime import datetime
from ..utils.logger import logger
from ..utils.video import get_video_info

class VideoStatus(Enum):
    PENDING = "待发布"
    PUBLISHING = "发布中"
    PUBLISHED = "已发布"
    FAILED = "发布失败"

class Video:
    def __init__(self, path: str):
        self.path = path
        self.name = os.path.basename(path)
        self.status = VideoStatus.PENDING
        self.info = get_video_info(path)
        self.publish_time = None
        self.error = None

class ManualPublishManager:
    def __init__(self):
        self.videos: List[Video] = []
        self.video_directory: Optional[str] = None
        self._logger = logger

    def set_video_directory(self, directory: str) -> bool:
        """设置视频目录"""
        try:
            if not os.path.exists(directory):
                os.makedirs(directory)
            
            self.video_directory = directory
            self.refresh_videos()
            return True
            
        except Exception as e:
            self._logger.error(f"设置视频目录失败: {str(e)}")
            return False

    def refresh_videos(self):
        """刷新视频列表"""
        try:
            if not self.video_directory:
                return
                
            self.videos.clear()
            
            # 遍历目录中的视频文件
            for filename in os.listdir(self.video_directory):
                file_path = os.path.join(self.video_directory, filename)
                if os.path.isfile(file_path) and self._is_video_file(filename):
                    self.videos.append(Video(file_path))
                    
            self._logger.info(f"刷新视频列表完成，共{len(self.videos)}个视频")
            
        except Exception as e:
            self._logger.error(f"刷新视频列表失败: {str(e)}")

    def _is_video_file(self, filename: str) -> bool:
        """检查是否为视频文件"""
        video_extensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv']
        return any(filename.lower().endswith(ext) for ext in video_extensions)

    def get_video_by_path(self, path: str) -> Optional[Video]:
        """根据路径获取视频对象"""
        return next((v for v in self.videos if v.path == path), None)

    def update_video_status(self, video: Video, status: VideoStatus, error: str = None):
        """更新视频状态"""
        video.status = status
        if status == VideoStatus.PUBLISHED:
            video.publish_time = datetime.now()
        if error:
            video.error = error
            self._logger.error(f"视频 {video.name} 发布失败: {error}")
        else:
            video.error = None
            self._logger.info(f"视频 {video.name} 状态更新为: {status.value}")

    def start_publish(self, video_paths: List[str], platform: str) -> bool:
        """开始发布视频"""
        try:
            for path in video_paths:
                video = self.get_video_by_path(path)
                if not video:
                    continue
                    
                self.update_video_status(video, VideoStatus.PUBLISHING)
                
                # TODO: 实现具体的发布逻辑
                # 根据不同平台调用相应的发布方法
                
                self.update_video_status(video, VideoStatus.PUBLISHED)
                
            return True
            
        except Exception as e:
            self._logger.error(f"发布视频失败: {str(e)}")
            return False

    def get_publish_history(self) -> List[Dict[str, Any]]:
        """获取发布历史"""
        history = []
        for video in self.videos:
            if video.status != VideoStatus.PENDING:
                history.append({
                    'name': video.name,
                    'path': video.path,
                    'status': video.status.value,
                    'publish_time': video.publish_time.isoformat() if video.publish_time else None,
                    'error': video.error
                })
        return history

# 创建全局发布管理器实例
manual_publish_manager = ManualPublishManager()

# 导出便捷函数
def set_video_directory(directory: str) -> bool:
    return manual_publish_manager.set_video_directory(directory)

def refresh_videos():
    manual_publish_manager.refresh_videos()

def get_video_by_path(path: str) -> Optional[Video]:
    return manual_publish_manager.get_video_by_path(path)

def start_publish(video_paths: List[str], platform: str) -> bool:
    return manual_publish_manager.start_publish(video_paths, platform)

def get_publish_history() -> List[Dict[str, Any]]:
    return manual_publish_manager.get_publish_history()
